package com.qujia.station.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.DesensitizedUtil;
import com.qujia.common.core.domain.AjaxResult;
import com.qujia.common.core.redis.RedisCache;
import com.qujia.common.exception.CustomException;
import com.qujia.customer.domain.CustomerCardUseRecord;
import com.qujia.customer.domain.ElectronicCardRefundRecord;
import com.qujia.customer.mapper.ElectronicCardRefundRecordMapper;
import com.qujia.customer.service.ICustomerElectronicCardService;
import com.qujia.integral.domain.CustomerPointsRecord;
import com.qujia.integral.service.ICustomerPointsRecordService;
import com.qujia.station.domain.*;
import com.qujia.station.enums.PrintEnum;
import com.qujia.station.mapper.PresentAmountRecordMapper;
import com.qujia.station.mapper.StationMapper;
import com.qujia.station.service.*;
import com.qujia.station.utils.FeiEPrinterUtil;
import com.qujia.station.utils.Methods;
import com.qujia.station.utils.YiLianYunPrinterUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrderPrintSerivceImpl implements OrderPrintService {
    @Resource
    private IPayOrderService payOrderService;

    @Resource
    private IPayOrderHistoryService payOrderHistoryService;

    @Resource
    private IStationDeviceManageService stationDeviceManageService;

    @Resource
    private ICustomerElectronicCardService customerElectronicCardService;

    @Resource
    private ICustomerPointsRecordService customerPointsRecordService;

//    @Resource
//    private IEnterpriseService enterpriseService;
//
//    @Resource
//    private IAppUserInfoUserService appUserInfoUserService;

    @Resource
    private IOilService oilService;

    @Resource
    private RedisCache redisCache;

    @Resource
    private StationMapper stationMapper;

    @Resource
    private PresentAmountRecordMapper presentAmountRecordMapper;

    @Resource
    private ElectronicCardRefundRecordMapper electronicCardRefundRecordMapper;

    @Override
    @Async("threadPoolTaskExecutor")
    public AjaxResult orderPrint(PayOrder payOrder, BigDecimal amount) {
        try {
//            PayOrder payOrder = payOrderService.selectPayOrderForFeiEById(payOrderParam.getOrderId());
//            if(payOrder == null){
//                payOrder = payOrderHistoryService.selectPayOrderForFeiEById(payOrderParam.getOrderId());
//            }
            log.info("订单信息{}",payOrder);
            StationDeviceManage stationDeviceManage = new StationDeviceManage();
            stationDeviceManage.setStationId(payOrder.getStationId());
            stationDeviceManage.setDeviceType("3");
            List<StationDeviceManage> stationDeviceManages = stationDeviceManageService.selectStationDeviceManageList(stationDeviceManage);
            log.info("小票机信息{}",stationDeviceManages);
            if (stationDeviceManages == null || stationDeviceManages.size() <= 0) {
                return AjaxResult.error("当前站点没有打印机");
            }
            //加油员ID
            String oilPersonnelId = payOrder.getOilPersonnelId();

            StringBuilder content = new StringBuilder();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            boolean guKeFlag = true;
            boolean shangHuflag = true;
            if ("1".equals(stationDeviceManages.get(0).getPrintType())) {
                shangHuflag = false;
            }
            if ("2".equals(stationDeviceManages.get(0).getPrintType())) {
                guKeFlag = false;
            }

            if (guKeFlag) {
                if (StringUtils.isNotBlank(payOrder.getStationName())) {
                    content.append("<BOLD><B>" + payOrder.getStationName() + "</B></BOLD><BR>");
                }
                content.append("--------【顾客联】--------<BR>");

                if (payOrder.getReceivableAmt() != null) {
                    content.append("<BOLD><B>原价：" + payOrder.getReceivableAmt() + "元</B></BOLD><BR>");
                }
                if (StringUtils.isNotBlank(payOrder.getOrderNo())) {
                    content.append("订单号：" + payOrder.getOrderNo() + "<BR>");
                }

                if (StringUtils.isNotBlank(payOrder.getOilGun())) {
                    content.append("油枪：" + payOrder.getOilGun() + "号枪<BR>");
                }

                Oil oil =  oilService.selectOilById(Long.valueOf(payOrder.getOilName()));

                if (Objects.nonNull(oil)) {
                    content.append("油品：" + oil.getOilName() + "<BR>");
                }

                if (StringUtils.isNotBlank(payOrder.getOilPirce() + "")) {
                    content.append("单价：" + payOrder.getOilPirce() + "(元/升)<BR>");
                }

                if (StringUtils.isNotBlank(payOrder.getOrderLiters() + "")) {
                    content.append("数量：" + payOrder.getOrderLiters() + "(L/kg)<BR>");
                }

                if (payOrder.getAmt() != null) {
                    content.append("实付：" + payOrder.getAmt() + "<BR>");
                }

//                if (payOrder.getReceivableAmt() != null) {
//                    content.append("应收款：" + payOrder.getReceivableAmt() + "<BR>");
//                }

                content.append("共优惠：" + payOrder.getDiscountAmt().add(payOrder.getDiscountCouponAmt()) + "<BR>");

                content.append("--------------------------------<BR>");
                //繁星订单
                if ("2".equals(payOrder.getUtmSource())) {
                    String phone = StringUtils.isNotBlank(payOrder.getCustomerPhone()) ? payOrder.getCustomerPhone() : "不详";
                    content.append("手机号：" + phone + "<BR>");

                } else if (StringUtils.isNotBlank(payOrder.getCustomerPhone())) {
                    content.append("手机号：" + payOrder.getCustomerPhone().replaceAll("(\\w{3})\\w*(\\w{4})", "$1****$2") + "<BR>");
                }

                if (StringUtils.isNotBlank(payOrder.getPayType())) {
                    if ("wx".equals(payOrder.getPayType())) {
                        content.append("支付方式：" + "微信" + "<BR>");
                    } else if ("zfb".equals(payOrder.getPayType())) {
                        content.append("支付方式：" + "支付宝" + "<BR>");
                    } else if ("yl".equals(payOrder.getPayType())) {
                        content.append("支付方式：" + "银联" + "<BR>");
                    } else if ("xj".equals(payOrder.getPayType())) {
                        content.append("支付方式：" + "现金" + "<BR>");
                    } else if ("dzk".equals(payOrder.getPayType())) {
                        content.append("支付方式：" + "电子卡" + "<BR>");
                    } else if ("hyk".equals(payOrder.getPayType())) {
                        content.append("支付方式：" + "实体卡" + "<BR>");
                    } else if ("dkq".equals(payOrder.getPayType())) {
                        content.append("支付方式：" + "实体卡支付" + "<BR>");
                    }

                }

//                String electronicCardAmt = getElectronicCardAmt(payOrder);
                content.append("实体卡余额：" + amount + "<BR>");

                CustomerPointsRecord customerPointsRecord = new CustomerPointsRecord();
                customerPointsRecord.setOrderNo(payOrder.getOrderNo());
                CustomerPointsRecord record = customerPointsRecordService.getOne(customerPointsRecord);

                String integral = Objects.nonNull(record) ? record.getIntegral().toString() : "0";

                content.append("获得积分：" + integral + "<BR>");

                if (payOrder.getCreatedDate() != null) {
                    content.append("下单时间：" + sdf.format(payOrder.getCreatedDate()) + "<BR>");
                }

                if (payOrder.getPayDate() != null) {
                    content.append("付款时间：" + sdf.format(payOrder.getPayDate()) + "<BR>");
                }

                content.append("--------------------------------<BR>");


                if (StringUtils.isNotBlank(payOrder.getOilPersonnel())) {
                    content.append("加油员：" + payOrder.getOilPersonnel() + "<BR>");
                }
                content.append("打印时间：" + DateUtil.now() + "<BR>");
                content.append("-------------------------<BR>");
                content.append("谢谢惠顾！欢迎下次再来~<BR>");
                content.append("<BR>");
                content.append("<BR>");
                content.append("<BR>");
            }
            if (shangHuflag) {
                if (StringUtils.isNotBlank(payOrder.getStationName())) {
                    content.append("<BOLD><B>" + payOrder.getStationName() + "</B></BOLD><BR>");
                }
                content.append("--------【商户联】--------<BR>");

                if (payOrder.getReceivableAmt() != null) {
                    content.append("<BOLD><B>原价：" + payOrder.getReceivableAmt() + "元</B></BOLD><BR>");
                }
                if (StringUtils.isNotBlank(payOrder.getOrderNo())) {
                    content.append("订单号：" + payOrder.getOrderNo() + "<BR>");
                }

                if (StringUtils.isNotBlank(payOrder.getOilGun())) {
                    content.append("油枪：" + payOrder.getOilGun() + "号枪<BR>");
                }

                Oil oil =  oilService.selectOilById(Long.valueOf(payOrder.getOilName()));

                if (Objects.nonNull(oil)) {
                    content.append("油品：" + oil.getOilName() + "<BR>");
                }

                if (StringUtils.isNotBlank(payOrder.getOilPirce() + "")) {
                    content.append("单价：" + payOrder.getOilPirce() + "(元/升)<BR>");
                }

                if (StringUtils.isNotBlank(payOrder.getOrderLiters() + "")) {
                    content.append("数量：" + payOrder.getOrderLiters() + "(L/kg)<BR>");
                }

                if (payOrder.getAmt() != null) {
                    content.append("实付：" + payOrder.getAmt() + "<BR>");
                }

//                if (payOrder.getReceivableAmt() != null) {
//                    content.append("应收款：" + payOrder.getReceivableAmt() + "<BR>");
//                }

                content.append("共优惠：" + payOrder.getDiscountAmt().add(payOrder.getDiscountCouponAmt()) + "<BR>");

                content.append("--------------------------------<BR>");

                //繁星订单
                if ("2".equals(payOrder.getUtmSource())) {
                    String phone = StringUtils.isNotBlank(payOrder.getCustomerPhone()) ? payOrder.getCustomerPhone() : "不详";
                    content.append("手机号：" + phone + "<BR>");

                } else if (StringUtils.isNotBlank(payOrder.getCustomerPhone())) {
                    content.append("手机号：" + payOrder.getCustomerPhone().replaceAll("(\\w{3})\\w*(\\w{4})", "$1****$2") + "<BR>");
                }

                if (StringUtils.isNotBlank(payOrder.getPayType())) {
                    if ("wx".equals(payOrder.getPayType())) {
                        content.append("支付方式：" + "微信" + "<BR>");
                    } else if ("zfb".equals(payOrder.getPayType())) {
                        content.append("支付方式：" + "支付宝" + "<BR>");
                    } else if ("yl".equals(payOrder.getPayType())) {
                        content.append("支付方式：" + "银联" + "<BR>");
                    } else if ("xj".equals(payOrder.getPayType())) {
                        content.append("支付方式：" + "现金" + "<BR>");
                    } else if ("dzk".equals(payOrder.getPayType())) {
                        content.append("支付方式：" + "电子卡" + "<BR>");
                    } else if ("hyk".equals(payOrder.getPayType())) {
                        content.append("支付方式：" + "实体卡" + "<BR>");
                    } else if ("cdk".equals(payOrder.getPayType())){
                        content.append("支付方式：" + "车队卡" + "<BR>");
                    }else if ("dkq".equals(payOrder.getPayType())) {
                        content.append("支付方式：" + "实体卡支付" + "<BR>");
                    }

                }
//                String electronicCardAmt = getElectronicCardAmt(payOrder);
                content.append("实体卡余额：" + amount + "<BR>");


                CustomerPointsRecord customerPointsRecord = new CustomerPointsRecord();
                customerPointsRecord.setOrderNo(payOrder.getOrderNo());
                CustomerPointsRecord record = customerPointsRecordService.getOne(customerPointsRecord);

                String integral = Objects.nonNull(record) ? record.getIntegral().toString() : "0";

                content.append("获得积分：" + integral + "<BR>");

                if (payOrder.getCreatedDate() != null) {
                    content.append("下单时间：" + sdf.format(payOrder.getCreatedDate()) + "<BR>");
                }

                if (payOrder.getPayDate() != null) {
                    content.append("付款时间：" + sdf.format(payOrder.getPayDate()) + "<BR>");
                }

                content.append("--------------------------------<BR>");


                if (StringUtils.isNotBlank(payOrder.getOilPersonnel())) {
                    content.append("加油员：" + payOrder.getOilPersonnel() + "<BR>");
                }
                content.append("打印时间：" + DateUtil.now() + "<BR>");
                content.append("-------------------------<BR>");
                content.append("谢谢惠顾！欢迎下次再来~<BR>");
                content.append("<BR>");
            }
            content.append("<BR>");
            content.append("<BR>");


            StationDeviceManage stationDeviceManagerRes;
            try {
                //筛选绑定了用户的小票机
                List<StationDeviceManage> manageWithUser = new ArrayList<>();
                if(payOrder!=null&&payOrder.getOilPersonnelId()!=null&&!"".equals(payOrder.getOilPersonnelId())){
                    manageWithUser = stationDeviceManages.stream().filter(device -> {
//                        if(StringUtils.isNotBlank(device.getUserIds())){
//                            List<String> userIdsList = Arrays.asList(device.getUserIds().split(","));
//                            return userIdsList.contains(oilPersonnelId);
//                        }
                        if(StationDeviceManage.bindingType_staff.equals(device.getBindingType())){
                            //当设备选择绑定员工，但未选择指定员工时，设备需播报或打印该设备所绑定的油站的所有订单
                            if(StringUtils.isBlank(device.getUserIds())){
                                return true;
                            } else {
                                //当设备选择绑定员工且选择了指定的员工时，设备仅播报或打印所绑定员工的订单
                                List<String> userIdsList = Arrays.asList(device.getUserIds().split(","));
                                return userIdsList.contains(payOrder.getOilPersonnelId());
                            }
                        } else if(StationDeviceManage.bindingType_gun.equals(device.getBindingType())){
                            //当设备选择绑定油枪时，但未选择指定油枪时，设备需播报或打印该设备所绑定的油站的所有订单
                            if(StringUtils.isBlank(device.getGunNo())){
                                return true;
                            } else {
                                //当设备选择绑定油枪时且选择了指定油枪时，设备仅播报或打印所绑定油枪的订单
                                List<String> gunNoList = Arrays.asList(device.getGunNo().split(","));
                                return gunNoList.contains(payOrder.getOilGun());
                            }
                        }
                        return false;
                    }).collect(Collectors.toList());
                }
                stationDeviceManagerRes  = CollectionUtils.isNotEmpty(manageWithUser) ? manageWithUser.get(0) : stationDeviceManages.get(0);
                log.info("筛选绑定用户的小票机信息：{}",stationDeviceManagerRes);
            }catch (Exception e){
                stationDeviceManagerRes = stationDeviceManages.get(0);
                log.error(e.getMessage());
            }

            String audio = stationDeviceManagerRes.getAudio();
            log.info("自定义语音audio:{}",audio);

            log.info("最终小票机信息：{}",stationDeviceManagerRes);
            String deviceFactory = stationDeviceManagerRes.getDeviceFactory();
            PrintEnum printEnum = PrintEnum.getByCode(deviceFactory);
            AjaxResult ajaxResult = AjaxResult.success();
            switch (printEnum){
                case YILIANYUN:
//
//                    HashMap<String, String> audioMap = new HashMap<>();
//                    audioMap.put("手机尾号", Objects.isNull(payOrder.getCustomerPhone()) ? "" : payOrder.getCustomerPhone().substring(7,11));
//                    audioMap.put("加油金额", payOrder.getReceivableAmt().toString() + "元");
//                    audioMap.put("支付金额", payOrder.getAmt().toString() + "元");
//                    audioMap.put("枪号", payOrder.getOilGun() + ",");
//                    audioMap.put("油品", payOrder.getOilName().replace("#","号") + ",");
//
//                    StringBuffer sb = new StringBuffer();
//                    try {
//                        String[] split = audio.split(";");
//
//                        //加油语音
//                        String oilOrderAudio = split[0];
//                        List<String> oilOrderAudioList = Arrays.asList(oilOrderAudio.split(","));
//                        sb.append("<audio>");
//                        for (String audioContent : oilOrderAudioList) {
//                            sb.append(audioContent + audioMap.get(audioContent));
//                        }
//                        sb.append("</audio>");
//                        log.info("播报语音：{}",sb);
//                    }catch (Exception e){
//                        sb = new StringBuffer("<audio>手机尾号").append(payOrder.getMobilePhone().substring(7, 11)).append("支付金额").append(payOrder.getAmt())
//                                .append("元").append("加油金额").append(payOrder.getReceivableAmt()).append("元").append(payOrder.getOilGun()).append("号油枪").append(payOrder.getOilName()).append("号油,</audio>");
//                    }
//
                    String ylyContent = content.toString().replace("<BR>", "\r\n").replace("</B></BOLD>","").replace("<BOLD><B>","");
//                    StringBuffer finalContent = sb.append(ylyContent);
//
//                    //初始化控制器类
//                    Methods m= Methods.getInstance();
//                    Object token = redisCache.getCacheObject("STATION:DEVICE:" + stationDeviceManagerRes.getClientId());
//
//                    Integer random6 = (int) ((Math.random() * 9 + 1) * 100000);
//
//                    if(Objects.nonNull(token)){
//                        String print = m.print(stationDeviceManagerRes.getDeviceNo(),finalContent.toString(),random6.toString());
//                        log.info("小票机返回值{}",print);
//                        org.json.JSONObject json = new JSONObject(print);
//                        if("0".equals(json.getString("error"))){
//                            break;
//                        }
//                    }
//
//                    //初始化终端信息
//                    m.init(stationDeviceManagerRes.getClientId(), stationDeviceManagerRes.getClientSecret());
//                    //获取token
//                    String refreshToken = m.getFreedomToken();
//                    //存入redis
//                    redisCache.setCacheObject("STATION:DEVICE:" + stationDeviceManagerRes.getClientId(),refreshToken,30, TimeUnit.DAYS);
//
//
//                    String print = m.print(stationDeviceManagerRes.getDeviceNo(), finalContent.toString(), random6.toString());
                    ajaxResult = YiLianYunPrinterUtil.print(ylyContent, stationDeviceManagerRes, payOrder);
                    break;

                case YILIANYUNK4:
                    String ylyContentK4 = content.toString().replace("<BR>", "\r\n").replace("</B></BOLD>","").replace("<BOLD><B>","");
                    ajaxResult = YiLianYunPrinterUtil.print(ylyContentK4, stationDeviceManagerRes, payOrder);
                    break;

                case FEIE:

                    String result = FeiEPrinterUtil.printReceipt(stationDeviceManages.get(0).getDeviceNo(), content.toString());
                    org.json.JSONObject resJson = new org.json.JSONObject(result);
                    if("ok".equals(resJson.get("msg"))){
                        ajaxResult = AjaxResult.success("补打小票成功");
                    }else {
                        ajaxResult = AjaxResult.success("补打小票失败");

                    }
                    break;
                default:
                    log.info("没有配置小票机，打印失败");
                    break;
//            return AjaxResult.success("打印成功");
            }
            int i=(int)ajaxResult.get("code");
            if (i==200){
                payOrderService.updatePayOrderPrintStatus(payOrder.getOrderNo());
            }

            return ajaxResult;
        }catch (Exception e){
            log.error(">小票打印异常", e);
            return AjaxResult.error(e.getMessage());

        }
//        return AjaxResult.success("打印成功");
    }

//    private String getElectronicCardAmt(PayOrder payOrder){
//        Enterprise enterprise = enterpriseService.selectEnterpriseById(payOrder.getEnterpriseId());
//        String cardUseRangeFlag = enterprise.getCardUseRangeFlag();
//
//        SysAppUserInfoUser sysAppUserInfoUser = appUserInfoUserService.selectAppUserInfoById(Long.valueOf(payOrder.getConsumerId()));
//        log.info("用户信息{}",sysAppUserInfoUser.toString());
//        CustomerElectronicCard customerElectronicCard = new CustomerElectronicCard();
//        customerElectronicCard.setCustomerNo(sysAppUserInfoUser.getMemberCode());
//
//        if("1".equals(cardUseRangeFlag)){
//            customerElectronicCard.setStationId(payOrder.getEnterpriseId());
//        }else if("2".equals(cardUseRangeFlag)){
//            customerElectronicCard.setStationId2(payOrder.getStationId());
//        }
//
//        String cardOilType =  "汽油".equals(payOrder.getOrderType()) ? "1" : "2";
//        customerElectronicCard.setCardOilsType(cardOilType);
//        log.info("customerElectronicCard:{}",customerElectronicCard);
//        CustomerElectronicCard electronicCardInfo =  customerElectronicCardService.getElectronicCardInfo(customerElectronicCard);
//        log.info("电子卡信息：{}",electronicCardInfo.toString());
//        return Objects.nonNull(electronicCardInfo) ? electronicCardInfo.getAmt().toString() : "0";
//    }
    private StationDeviceManage getStationDeviceManage(String stationId){
        log.info("打印退款小票");
        StationDeviceManage stationDeviceManager=new StationDeviceManage();
        stationDeviceManager.setStationId(Long.valueOf(stationId));
        stationDeviceManager.setDeviceType("3");
        List<StationDeviceManage> stationDeviceManages = stationDeviceManageService.selectStationDeviceManageList(stationDeviceManager);
        if(CollectionUtils.isEmpty(stationDeviceManages)){
            throw new CustomException("当前油站没有配置小票机");
        }
        return stationDeviceManages.get(0);
    }
    private StationDeviceManage getStationDeviceManage(String stationId,String gunNo){
        log.info("打印退款小票");
        StationDeviceManage stationDeviceManager=new StationDeviceManage();
        stationDeviceManager.setStationId(Long.valueOf(stationId));
        stationDeviceManager.setDeviceType("3");
        stationDeviceManager.setGunNo(gunNo);
        List<StationDeviceManage> stationDeviceManages = stationDeviceManageService.selectStationDeviceManageList(stationDeviceManager);
        if(CollectionUtils.isEmpty(stationDeviceManages)){
            throw new CustomException("当前油站没有配置小票机");
        }
        return stationDeviceManages.get(0);
    }

    @Override
    @Async("threadPoolTaskExecutor")
    public void printRefundElectrondOrder(CustomerCardUseRecord customerCardUseRecord, ElectronicCardRefundRecord refundRecorde) {

        StationDeviceManage stationDeviceManage = getStationDeviceManage(customerCardUseRecord.getStationId().toString());
        String refundPrintContent = getRefundElectricPrintContent(customerCardUseRecord, stationDeviceManage, refundRecorde);
        if(stationDeviceManage.getIsPrint() == 0){
            return;
        }
        printOrder(stationDeviceManage, refundPrintContent);

    }

    @Override
    @Async("threadPoolTaskExecutor")
    public void printRefundOrder(PayOrder payOrder) {
        log.info("退款订单信息【{}】", payOrder);
        StationDeviceManage stationDeviceManage = getStationDeviceManage(payOrder.getStationId().toString(),payOrder.getOilGun());
        String refundContent = getRefundContent(payOrder, stationDeviceManage);
        if(stationDeviceManage.getIsPrint() == 0){
            return;
        }
        printOrder(stationDeviceManage, refundContent);
    }

    private String getRefundContent(PayOrder payOrder, StationDeviceManage stationDeviceManage){
        StringBuilder content = new StringBuilder();
        String deviceFactory = stationDeviceManage.getDeviceFactory();
        PrintEnum printEnum = PrintEnum.getByCode(deviceFactory);

        log.info("小票机类型【{}】", printEnum);
        switch (printEnum){
            case YILIANYUNK4:
                content.append("<MS>0,0</MS>");
                content.append("<FS2><center>" + payOrder.getStationName() + "</center></FS2><BR>");
                content.append("<center>【消费退款】</center><BR>");
                break;
            case YILIANYUN:
                content.append("<MS>0,0</MS>");
                content.append("<FS2><center>" + payOrder.getStationName() + "</center></FS2><BR>");
                content.append("<center>【消费退款】</center><BR>");
                break;
            case FEIE:
                content.append("<BOLD><C><B>" + payOrder.getStationName() + "</B></C></BOLD><BR>");
                content.append("<C>【消费退款】</C><BR>");
                break;
        }
        content.append("--------------------------------<BR>");
        content.append("订单编号：").append(payOrder.getOrderNo()).append("<BR>");
        content.append("手机号  ：").append(DesensitizedUtil.mobilePhone(payOrder.getCustomerPhone())).append("<BR>");
        content.append("退款金额：").append(payOrder.getAmt()).append("元").append("<BR>");

        PresentAmountRecord presentAmountRecord = new PresentAmountRecord();
        presentAmountRecord.setOrderNo(payOrder.getOrderNo());
        List<PresentAmountRecord> presentAmountRecords = presentAmountRecordMapper.query(presentAmountRecord);


        content.append("赠送退款：").append(CollectionUtils.isEmpty(presentAmountRecords) ? "0" : presentAmountRecords.get(0).getPresentAmount()).append("元").append("<BR>");
        CustomerPointsRecord customerPointsRecord = new CustomerPointsRecord();
        customerPointsRecord.setOrderNo(payOrder.getOrderNo());
        CustomerPointsRecord customerPointsRecordRes = customerPointsRecordService.getOne(customerPointsRecord);
        content.append("积分退款：").append(Objects.nonNull(customerPointsRecordRes) ? customerPointsRecordRes.getIntegral() : "0").append("<BR>");
        content.append("退款时间：").append(DateUtil.now()).append("<BR>");
        content.append("--------------------------------<BR>");
        content.append("打印时间：").append(DateUtil.now()).append("<BR>");
        content.append("-------------------------<BR>");
        content.append("谢谢惠顾！欢迎下次再来~<BR>");
        content.append("<BR>");
        content.append("<BR>");
        content.append("<BR>");
        content.append("<BR>");
        content.append("<BR>");
        content.append("<BR>");
        content.append("<BR>");
        content.append("<BR>");
        if(!printEnum.equals(PrintEnum.FEIE)){
            return content.toString().replace("<BR>", "\r\n");
        }
        log.info("充值退款打印订单：【{}】", content.toString());
        return content.toString();
    }

    private String getRefundElectricPrintContent(CustomerCardUseRecord customerCardUseRecord, StationDeviceManage stationDeviceManage, ElectronicCardRefundRecord refundRecorde){
        log.info("退款打印小票,退款订单【{}】，原始订单:【{}】", customerCardUseRecord, refundRecorde);
        StringBuilder content = new StringBuilder();
        String deviceFactory = stationDeviceManage.getDeviceFactory();
        PrintEnum printEnum = PrintEnum.getByCode(deviceFactory);
        log.info("小票机类型【{}】", printEnum);

        Station station = stationMapper.selectStationById(Long.valueOf(customerCardUseRecord.getStationId()));

        switch (printEnum){
            case YILIANYUNK4:
                content.append("<MS>0,0</MS>");
                content.append("<FS2><center>" + station.getStationName() + "</center></FS2><BR>");
                content.append("<center>【充值退款】</center><BR>");
                break;
            case YILIANYUN:
                content.append("<MS>0,0</MS>");
                content.append("<FS2><center>" + station.getStationName() + "</center></FS2><BR>");
                content.append("<center>【充值退款】</center><BR>");
                break;
            case FEIE:
                content.append("<BOLD><C><B>" + station.getStationName() + "</B></C></BOLD><BR>");
                content.append("<C>【充值退款】</C><BR>");
                break;
        }
        content.append("--------------------------------<BR>");
        content.append("订单编号：").append(customerCardUseRecord.getOrderNo()).append("<BR>");
        content.append("手机号  ：").append(DesensitizedUtil.mobilePhone(customerCardUseRecord.getMobilePhone())).append("<BR>");
        content.append("退款金额：").append(customerCardUseRecord.getAmt()).append("元").append("<BR>");
        content.append("赠送退款：").append(customerCardUseRecord.getPresentAmt()).append("元").append("<BR>");


        CustomerPointsRecord customerPointsRecordQuery = new CustomerPointsRecord();
        customerPointsRecordQuery.setOrderNo(refundRecorde.getOriginOrderNo());
        CustomerPointsRecord customerPointsRecordRes = customerPointsRecordService.getOne(customerPointsRecordQuery);

        content.append("积分退款：").append(Objects.nonNull(customerPointsRecordRes) ? customerPointsRecordRes.getIntegral() : "0").append("<BR>");
        content.append("退款时间：").append(DateUtil.format(refundRecorde.getRefundTime(), DatePattern.NORM_DATETIME_PATTERN)).append("<BR>");
        content.append("--------------------------------<BR>");
        content.append("打印时间：").append(DateUtil.now()).append("<BR>");
        content.append("-------------------------<BR>");
        content.append("谢谢惠顾！欢迎下次再来~<BR>");
        content.append("<BR>");
        content.append("<BR>");
        content.append("<BR>");
        content.append("<BR>");
        content.append("<BR>");
        content.append("<BR>");
        content.append("<BR>");
        content.append("<BR>");
        if(!printEnum.equals(PrintEnum.FEIE)){
            return content.toString().replace("<BR>", "\r\n");
        }
        log.info("充值退款打印订单：【{}】", content.toString());
        return content.toString();
    }

    private void printOrder(StationDeviceManage stationDeviceManage, String content){
        log.info("小票机信息【{}】", stationDeviceManage);
        String deviceFactory = stationDeviceManage.getDeviceFactory();
        PrintEnum printEnum = PrintEnum.getByCode(deviceFactory);

        String printRes = "";
        AjaxResult ajaxResult = AjaxResult.success();
        switch (printEnum){
            case YILIANYUNK4:

                Integer random6K4 = (int) ((Math.random() * 9 + 1) * 100000);
                //初始化控制器类
                Methods mK4= Methods.getInstance();
                Object tokenK4 = redisCache.getCacheObject("STATION:DEVICE:" + stationDeviceManage.getClientId());
                log.info("token:{}",tokenK4);
                if(Objects.nonNull(tokenK4)){
                    String print = mK4.print(stationDeviceManage.getClientId(),stationDeviceManage.getDeviceNo(), content, random6K4.toString(), tokenK4.toString());
                    log.info("小票机返回值{}",print);
                    org.json.JSONObject json = new org.json.JSONObject(print);
                    if("0".equals(json.getString("error"))){
                        break;
                    }
                }

                //初始化终端信息
                mK4.init(stationDeviceManage.getClientId(), stationDeviceManage.getClientSecret());
                //获取token
                String refreshTokenK4 = mK4.getFreedomToken();
                log.info("新的token{}",refreshTokenK4);
                //存入redis
                redisCache.setCacheObject("STATION:DEVICE:" + stationDeviceManage.getClientId(),refreshTokenK4,30, TimeUnit.DAYS);


                String printK4 = mK4.print(stationDeviceManage.getDeviceNo(), content, random6K4.toString());
                log.info("小票机返回值2{}",printK4);

                break;

            case YILIANYUN:
                Integer random6 = (int) ((Math.random() * 9 + 1) * 100000);
                //初始化控制器类
                Methods m= Methods.getInstance();
                Object token = redisCache.getCacheObject("STATION:DEVICE:" + stationDeviceManage.getClientId());
                log.info("token:{}",token);
                if(Objects.nonNull(token)){
                    String print = m.print(stationDeviceManage.getClientId(),stationDeviceManage.getDeviceNo(), content, random6.toString(), token.toString());
                    log.info("小票机返回值{}",print);
                    org.json.JSONObject json = new org.json.JSONObject(print);
                    if("0".equals(json.getString("error"))){
                        break;
                    }
                }

                //初始化终端信息
                m.init(stationDeviceManage.getClientId(), stationDeviceManage.getClientSecret());
                //获取token
                String refreshToken = m.getFreedomToken();
                log.info("新的token{}",refreshToken);
                //存入redis
                redisCache.setCacheObject("STATION:DEVICE:" + stationDeviceManage.getClientId(),refreshToken,30, TimeUnit.DAYS);


                String print = m.print(stationDeviceManage.getDeviceNo(), content, random6.toString());
                log.info("小票机返回值2{}",print);
                break;
            case FEIE:
                String result = FeiEPrinterUtil.printReceipt(stationDeviceManage.getDeviceNo(), content.toString());
                org.json.JSONObject resJson = new org.json.JSONObject(result);
                if("ok".equals(resJson.get("msg"))){
                    printRes = "补打小票成功";
                    ajaxResult = AjaxResult.success(printRes);
                }else {
                    printRes = "补打小票失败";
                    ajaxResult = AjaxResult.error(printRes);
                }

                break;
            default:
                log.info("没有配置小票机，打印失败");
                break;
        }
    }
}
